package ccm.communicate.tcp;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class TcpClientConfigJPanel extends JPanel implements ActionListener
{
    /**
     * 保存被控制的TCP连接
     */
    TcpClient  tcpClient;
    /**
     * 保存主机地址的输入框
     */
    JTextField hostJTextField;
    /**
     * 保存主机端口的输入框
     */
    JTextField portJTextField;

    TcpClientConfigJPanel(TcpClient tcpClientIn) throws NullPointerException
    {
        super();
        if(tcpClientIn==null)
            throw new NullPointerException();
        tcpClient=tcpClientIn;
        setLayout(new GridLayout(2,1));
        /*
          生成主机的面板
         */
        JPanel hostJTextFieldJPanel=new JPanel();
        add(hostJTextFieldJPanel);
        hostJTextFieldJPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
        hostJTextFieldJPanel.add(new JLabel("主机地址"));
        hostJTextField=new JTextField();
        hostJTextFieldJPanel.add(hostJTextField);
        hostJTextField.addActionListener(this);

        /*
          生成主机的面板
         */
        JPanel portJTextFieldJPanel=new JPanel();
        add(portJTextFieldJPanel);
        portJTextFieldJPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
        portJTextFieldJPanel.add(new JLabel("主机端口"));
        portJTextField=new JTextField();
        portJTextFieldJPanel.add(portJTextField);
        portJTextField.addActionListener(this);

        hostJTextField.setText(tcpClient.getHost());
        portJTextField.setText(String.format("%d",tcpClient.getPort()));
        updatePreferredSize();
    }

    /**
     * 更新各个面板的宽度
     */
    private void updatePreferredSize()
    {
        int width=hostJTextField.getPreferredSize().width;
        width=Math.max(width,portJTextField.getPreferredSize().width);
        hostJTextField.setPreferredSize(new Dimension(width,hostJTextField.getPreferredSize().height));
        portJTextField.setPreferredSize(hostJTextField.getPreferredSize());
    }

    public void actionPerformed(ActionEvent e)
    {
        if(e.getSource().equals(hostJTextField))
        {
            tcpClient.setHost(hostJTextField.getText());
        }
        else if(e.getSource().equals(portJTextField))
        {
            try
            {
                tcpClient.setPort(Integer.parseInt(portJTextField.getText()));
            }catch(NumberFormatException ex)
            {
                JOptionPane.showMessageDialog(this,"不合法的端口","错误",JOptionPane.ERROR_MESSAGE);
                ex.printStackTrace();
            }
        }
        updatePreferredSize();
    }
}
